﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Sworm
{
    public class ParamCollector
    {
        private int count = 100;

        public ParamCollector()
        {
            Params = new List<Param>();
        }

        public IList<Param> Params { get; protected set; }

        private static Regex regex = new Regex(@"@\w+", RegexOptions.Compiled);

        // This takes sql by ref so it can rewrite it to make sure we don't have duplicate params.
        public void Collect(ref string sql, object[] args)
        {
            var consumedArgs = new bool[args.Length];

            sql = regex.Replace(sql, m =>
            {
                string name = m.Value.Substring(1);
                int position;
                if (!int.TryParse(name, out position))
                {
                    throw new InvalidQueryException("Invalid parameter - syntax is @2 where 2 is the index of the param value");
                }

                if (position < 0 || position >= args.Length)
                {
                    throw new InvalidQueryException(string.Format(
                        "Parameter {0} is out of range (args.Length is {1})", m.Value, args.Length));
                }

                count++;
                consumedArgs[position] = true;
                var parm = new Param(count.ToString(), args[position]);
                Params.Add(parm);
                return "@" + parm.Name;
            });

            for (int i = 0; i < consumedArgs.Length; i++)
            {
                if (!consumedArgs[i])
                {
                    throw new InvalidQueryException(string.Format(
                        "The argument at position {0} was not used", i));
                }
            }
        }
    }
}
